
package net.vinote.smart.platform.service.dw.html;

import java.util.HashMap;
import java.util.Map;

import net.vinote.smart.platform.comm.StringFunction;


public abstract class HtmlTemplate
{
	protected Map<String, String> placeholder = new HashMap<String, String>();

	private StringBuffer content = new StringBuffer("");// 内容

	protected Map<String, String> attributes = new HashMap<String, String>();

	public String getHtml()
	{
		initBasePlaceHolder();
		String html = getHtmlTemplate();
		for (String key : placeholder.keySet())
		{
			html = html.replace(key,
					StringFunction.nullToBlank(placeholder.get(key)));
		}
		return html;
	}

	/**
	 * 初始化基本占位符
	 */
	private void initBasePlaceHolder()
	{
		StringBuffer sb = new StringBuffer();
		for (String key : attributes.keySet())
		{
			sb.append(key).append("='").append(attributes.get(key))
					.append("' ");
		}
		placeholder.put("#attributes", sb.toString());
		placeholder.put("#content", content == null ? "" : getContent());
		initPlaceHolder();
	}

	protected abstract String getHtmlTemplate();

	protected abstract void initPlaceHolder();

	public String getContent()
	{
		return content.toString();
	}

	public void addContent(String content)
	{
		this.content.append(content);
	}

	public void setContent(String content)
	{
		this.content.setLength(0);
		this.content.append(content);
	}

	public void setStyle(String style)
	{
		attributes.put("style", style);
	}

	/**
	 * function中如引用字符串,则必须使用单引号
	 */
	public void addEvent(UIEvent event, String function)
	{
		attributes.put(event.getName(), function);
	}

	public String getAttribute(String attr)
	{
		return attributes.get(attr);
	}

	public Map<String, String> getAttributes()
	{
		return attributes;
	}

	public void setAttribute(String attr, String value)
	{
		this.attributes.put(attr, value);
	}

	public void addAttributes(Map<String, String> attributes)
	{
		this.attributes.putAll(attributes);
	}

	public void setAttributes(Map<String, String> attributes)
	{
		this.attributes = attributes;
	}

	public void removeAttribute(String attr)
	{
		this.attributes.remove(attr);
	}

	public String getId()
	{
		return getAttribute("id");
	}

	public void setId(String id)
	{
		setAttribute("id", id);
	}
}
